<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-13 17:02:25
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-08-08
-->
<template>
  <div>
    <LayoutPanel class="private-common-wrapper">
      <div slot="title" class="title">
        <div class="title-content">
          <span>{{ $t('debugLog.title') }}</span>
          <a-tooltip :title="$t('debugLog.tip')">
            <icon-font type="ic-help" />
          </a-tooltip>
        </div>
      </div>
      <div class="account-warpper">
        <div>
          <a-radio-group v-model="userType" :disabled="isLoading">
            <a-radio value="all"> {{ $t('debugLog.all') }} </a-radio>
            <a-radio value="specify"> {{ $t('debugLog.specify') }} </a-radio>
          </a-radio-group>
        </div>
        <div v-show="userType === 'specify'">
          <a-input
            v-model="debugAccount"
            :placeholder="$t('common.account')"
            :disabled="isLoading"
          />
        </div>
        <div>
          <a-button type="primary" @click="onDebug" :disabled="isLoading">
            {{ $t('debugLog.collect') }}
          </a-button>
          <a-button @click="onClear" :disabled="isLoading">
            {{ $t('debugLog.clear') }}
          </a-button>
          <a-button @click="onStop" v-show="isLoading">
            {{ $t('debugLog.stop') }}
          </a-button>
        </div>
      </div>
      <LayoutPanel class="result-wrapper">
        <div slot="title" class="log-title">
          <span>{{ $t('debugLog.result') }}</span>
          <a
            v-show="!isLoading && logResult && logResult.length > 0"
            class="log-download"
            @click="onDownloadTextFile"
          >
            <icon-font type="ic-download" />
            {{ $t('common.download') }}
          </a>
        </div>
        <div class="loading-wrapper" v-show="isLoading">
          <a-spin size="large">
            <a-icon
              slot="indicator"
              type="loading"
              style="font-size: 80px"
              spin
            />
          </a-spin>
          <span>{{ $t('debugLog.collecting') }}</span>
        </div>
        <div
          style="text-align: left"
          v-show="!isLoading && logResult && logResult.length > 0"
        >
          <a-textarea
            style="width: 100%; max-width: 1200px"
            v-model="logResult"
            :auto-size="{ minRows: 20, maxRows: 20 }"
          >
          </a-textarea>
        </div>
        <div class="no-data-wrapper" v-show="!isLoading && logResult === null">
          <img alt src="@/project/authSys/assets/images/common/noData.png" />
          <span>{{ $t('debugLog.noData') }}</span>
        </div>
        <div class="no-data-wrapper" v-show="!isLoading && logResult === ''">
          <img alt src="@/project/authSys/assets/images/common/noResult.png" />
          <span>{{ $t('debugLog.noResult') }}</span>
        </div>
      </LayoutPanel>
    </LayoutPanel>
  </div>
</template>

<script>
import { requestHttp, maccApi } from '@utils/index';
import LayoutPanel from '@views/common/deviceDetail/components/components/layoutPanel.vue';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import RjModal from '@components/rj-modal/index.vue';
export default {
  name: 'portalClient',
  mixins: [authSysMixin],
  components: {
    LayoutPanel,
  },
  data() {
    return {
      userType: 'all',
      logResult: '',
      isTableLoading: false,
      queryParamObj: {
        username: '',
      },
      onlineClientNum: 0,
      debugAccount: '',
      debugUuid: '',
      loadingTime: 99,
      isLoading: false,

      collectTimer: null, // 定时器
      isDisabled: false,
    };
  },
  async mounted() {
    const debugLogObj = sessionStorage.getItem('IM_DEBUG_LOG');
    if (debugLogObj) {
      const { debugUuid, createTime } = JSON.parse(debugLogObj);
      const currentTime = new Date().getTime();
      if (currentTime - createTime < 99 * 1000) {
        this.debugUuid = debugUuid;
        this.startCollecting();
      }
    }
    // this.getLogList();
    // this.getPortalClientCount();
  },
  computed: {
    authDeviceGroupMap() {
      const tempMap = {};
      for (const group of this.authDeviceGroups) {
        tempMap[group.id] = group.name;
      }
      return tempMap;
    },
  },

  destroyed() {
    if (this.collectTimer) {
      this.stopCollecting();
    }
  },

  methods: {
    onStop() {
      RjModal.confirm({
        title: this.$t('debugLog.stopTitle'),
        content: () => {
          return this.$t('debugLog.stopTip');
        },
        onOk: async () => {
          this.stopCollecting();
        },
      });
    },
    onDownloadTextFile() {
      const text = this.logResult;
      const filename = 'authSysDebug.log';
      // 创建一个新的 Blob 对象，类型为 'text/plain'
      const blob = new Blob([text], { type: 'text/plain' });

      // 创建一个指向 Blob 的 URL
      const url = URL.createObjectURL(blob);

      // 创建一个隐藏的 <a> 标签
      const link = document.createElement('a');

      // 设置 <a> 标签的 href 属性为 Blob 的 URL
      link.href = url;

      // 设置下载的文件名
      link.download = filename;

      // 添加 <a> 标签到页面
      document.body.appendChild(link);

      // 模拟点击 <a> 标签来触发下载
      link.click();

      // 清理：删除 <a> 标签和释放 Blob URL
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    },
    async onDebug() {
      const res = await this.requestHttpAuth({
        api: maccApi.MACC_DEBUG_POST_API,
        method: 'POST',
        params: {
          username: this.debugAccount,
        },
      });
      if (res.data.success) {
        this.debugUuid = res.data.result;
        this.startCollecting();

        sessionStorage.setItem(
          'IM_DEBUG_LOG',
          JSON.stringify({
            debugUuid: this.debugUuid,
            createTime: new Date().getTime(),
          })
        );
        // this.debugUuid = 'weSKWMI1gLnivvs7gWz';
      } else {
        this.$message.warning(res.data.message);
      }
    },
    startCollecting() {
      this.isLoading = true;
      this.loadingTime = 99;
      this.collectTimer = setInterval(() => {
        this.loadingTime--;
        if (this.loadingTime === 0) {
          this.stopCollecting();
        } else {
          if (this.loadingTime !== 99 && this.loadingTime % 10 === 0) {
            this.getLogList();
          }
        }
      }, 1000);
    },
    stopCollecting() {
      this.isLoading = false;
      clearInterval(this.collectTimer);
    },
    onClear() {
      this.debugAccount = '';
      this.logResult = '';
      this.$message.success(this.$t('common.optSuccess'));
    },
    getAuthDeviceGroupName(value) {
      const groupName = this.authDeviceGroupMap[value];
      return groupName ? groupName : '';
    },
    async getLogList() {
      this.isTableLoading = true;
      const res = await this.requestHttpAuth({
        api: maccApi.RADIUS_DEBUG_GET_API,
        method: 'GET',
        replaces: {
          uuid: this.debugUuid,
        },
      });
      this.isTableLoading = false;
      if (res.data.success) {
        sessionStorage.removeItem('IM_DEBUG_LOG');
        this.logResult = res.data.result;
        this.stopCollecting();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.title-content {
  display: flex;
  align-items: center;
  gap: 8px;
}
.log-title {
  display: flex;
  justify-content: space-between;
  .log-download {
    color: @theme-color;
  }
}
.loading-wrapper {
  margin-top: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  .loading-time {
    position: relative;
    text-align: center;
    left: 96px;
    font-size: 18px;
    font-weight: 500;
    width: 80px;
  }
}
.no-data-wrapper {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
  img {
    width: 160px;
    margin-bottom: 16px;
  }
  span {
    color: #999;
  }
}
.result-wrapper {
  margin-top: 24px;
  /deep/.layout-panel-head {
    font-size: 14px;
    max-width: 1200px;
  }
  /deep/.layout-panel-head::before {
    display: block;
  }
}
.ant-input {
  width: 320px;
  margin-right: 16px;
}
.account-warpper {
  background: #eaf0ff;
  border-radius: 8px;
  padding: 24px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
  flex-direction: column;
  .ant-btn + .ant-btn {
    margin-left: 16px;
  }
}
.private-common-wrapper {
  overflow-y: auto;
  height: 100%;
  padding: 16px;
  .title {
    display: flex;
    justify-content: space-between;
  }
}
.log-opt-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}
.down-arrow {
  color: @success-color;
}
.up-arrow {
  color: @theme-color;
}
.status {
  display: flex;
  align-items: center;
  gap: 4px;
  &::before {
    content: '';
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 3px;
  }
  &.online {
    &::before {
      background: @success-color;
    }
  }
  &.offline {
    &::before {
      background: @component-border;
    }
  }
}
.w-200 {
  width: 200px;
}
</style>
